package com.infisight.hudprojector.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.google.gson.Gson;
import com.infisight.hudprojector.R;
import com.infisight.hudprojector.adapter.MusicAdapter;
import com.infisight.hudprojector.data.DataMusicClass;
import com.infisight.hudprojector.data.MusicTypeClass;
import com.infisight.hudprojector.data.SpeechVoiceData;
import com.infisight.hudprojector.data.VoiceDataClass;
import com.infisight.hudprojector.kdxfspeech.SpeechVoiceCompound;
import com.infisight.hudprojector.service.MusicService;
import com.infisight.hudprojector.util.CommonUtil;
import com.infisight.hudprojector.util.Constants;
import com.infisight.hudprojector.util.MusicList;

/**
 * 项目名称 : FRMusic2
 * 
 * @author 作者 : fengrui
 * @date 创建时间：2015年8月18日 下午3:27:18
 * @version 1.0
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MusicFragment extends Fragment implements OnClickListener {

	SharedPreferences sp;
	protected static final String TAG = "MusicFragment";
	// 歌曲列表
	private ListView listView;
	// // 下一页
	// private Button btn_next_page;
	// // 按照歌曲名搜索
	// private Button btn_song;
	// // 按照歌手搜索歌曲
	// private Button btn_singer;
	// // 所有歌曲
	// private Button btn_all;
	// // 上一页
	// private Button btn_last_page;
	// // 选择第一条
	// private Button btn_choose_item;
	// 歌曲列表
	private List<DataMusicClass> listMusic;

	// 用来存播放列表的类型
	private List<DataMusicClass> listTypeMusic = null;

	private String SearchType = null;
	// 歌曲项的适配器
	private MusicAdapter adapter;
	// 当前列表顶部
	private int up = 0;
	// 当前列表底部
	private int down = 0;

	public static int musicLsts = 0;
	Gson gson = null;
	SpeechVoiceCompound svc = null;

	/**
	 * 创造唯一实例
	 * 
	 * @param musicInfo
	 * @return
	 */
	public static MusicFragment newInstance(String musicInfo) {
		MusicFragment fragment = new MusicFragment();
		Bundle args = new Bundle();
		args.putString("musicInfo", musicInfo);
		fragment.setArguments(args);
		return fragment;
	}

	/**
	 * 构造函数
	 */
	public MusicFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		sp = getActivity().getSharedPreferences("bg_music_info", 0);
		init();
		super.onActivityCreated(savedInstanceState);
	}

	/**
	 * 初始化控件
	 */
	private void init() {
		listView = (ListView) getActivity().findViewById(R.id.listAllMusic);
		// btn_next_page = (Button) getActivity().findViewById(R.id.btn1);
		// btn_last_page = (Button) getActivity().findViewById(R.id.btn5);
		// btn_choose_item = (Button) getActivity().findViewById(R.id.btn6);
		// btn_song = (Button) getActivity().findViewById(R.id.btn2);
		// btn_singer = (Button) getActivity().findViewById(R.id.btn3);
		// btn_all = (Button) getActivity().findViewById(R.id.btn4);
		//
		// btn_next_page.setOnClickListener(this);
		// btn_song.setOnClickListener(this);
		// btn_singer.setOnClickListener(this);
		// btn_all.setOnClickListener(this);
		// btn_last_page.setOnClickListener(this);
		// btn_choose_item.setOnClickListener(this);

		getAllMusic();

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// Intent intent = new Intent(getActivity(),
				// MusicActivity.class);
				// intent.putExtra("id", arg2);
				// startActivity(intent);

				SpeechVoiceData data = new SpeechVoiceData();
				data.setCommand(Constants.MAIN_MUSIC_PLAY_COM);
				if (listTypeMusic != null) {
					MusicTypeClass mtc = new MusicTypeClass(String
							.valueOf(arg2), gson.toJson(listTypeMusic));
					data.setValue(gson.toJson(mtc));
				} else {
					data.setValue(String.valueOf(arg2 + up));
				}
				sp.edit().putInt("currentMusic", arg2 + up).commit();// 首次保存播放歌曲
				CommonUtil.processBroadcast(getActivity(), data);
			}
		});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		svc = SpeechVoiceCompound.getInstance(getActivity(), null, null);
		return inflater.inflate(R.layout.music_fragment, container, false);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		getActivity().registerReceiver(musicReceiver, makeNewMsgIntentFilter());
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(musicReceiver);
		super.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}

	BroadcastReceiver musicReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			gson = new Gson();
			final String action = intent.getAction();
			SpeechVoiceData svd;
			VoiceDataClass vdc;
			if (Constants.MAIN_MUSIC_ACTION.equals(action)
					|| Constants.COMMON_UTIL_ACTION.equals(action)) {
				svd = gson.fromJson(intent.getStringExtra(action),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

				if (listMusic != null || listMusic.size() != 0) {
					Intent intent2 = new Intent(getActivity(),
							MusicService.class);
					// 上一页
					if (vdc.getType().equals(Constants.F_R_MUSIC_PAGE_DOWN[0])) {
						Log.i("TAG", "下一页");
						setDownPage(listMusic);
					}
					// 下一页
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_PAGE_UP[0])) {
						Log.i("TAG", "上一页");
						setUpPage(listMusic);
					}
					// 搜索
					else if (vdc.getType().equals(
							Constants.F_R_SEARCH_CONTENT[0])) {
						Log.i(TAG, vdc.getValue());

						if (getSearchMusicSinger(vdc.getValue())) {
							svc.startSpeaking("已找到歌手");
						} else if (getSearchMusicSong(vdc.getValue())) {
							svc.startSpeaking("已找到歌曲");
						} else {
							svc.startSpeaking("未找到歌手或歌曲");
						}
						// ;
					}
					// 选择第几条
					else if (vdc.getType().equals(Constants.F_R_CHOOSE_ITEM[0])) {
						Log.i("TAG", "选择第几条");
						String index = String.valueOf(CommonUtil.getIndex(vdc
								.getValue()) + up);// 获取歌曲id
						SpeechVoiceData data = new SpeechVoiceData();
						data.setCommand(Constants.MAIN_MUSIC_PLAY_COM);
						if (listTypeMusic != null) {
							MusicTypeClass mtc = new MusicTypeClass(index,
									gson.toJson(listTypeMusic));
							data.setValue(gson.toJson(mtc));
						} else {
							data.setValue(index);
						}
						sp.edit()
								.putInt("currentMusic",
										CommonUtil.getIndex(vdc.getValue())
												+ up).commit();// 首次保存播放歌曲
						CommonUtil.processBroadcast(getActivity(), data);
					}
					// 停止播放
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_STOP_PLAY[0])) {
						Log.i("TAG", "F_R_MUSIC_STOP_PLAY----停止播放");
						intent2.putExtra("play", "pause");
						getActivity().startService(intent2);
					}
					// 继续播放
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_CONTINUE_PLAY[0])) {
						intent2.putExtra("play", "playing");
						intent2.putExtra("id", sp.getInt("currentMusic", 0));
						getActivity().startService(intent2);
					}
					// 下一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_NEXT_MUSIC_PLAY[0])) {
						intent2.putExtra("play", "next");
						intent2.putExtra("id", sp.getInt("currentMusic", 0) + 1);
						getActivity().startService(intent2);
					}
					// 上一首
					else if (vdc.getType().equals(
							Constants.F_R_MUSIC_LAST_MUSIC_PLAY[0])) {
						int index = sp.getInt("currentMusic", 0) - 1;
						if (index < 0) {
							index = 0;
						}
						intent2.putExtra("play", "last");
						intent2.putExtra("id", index);
						getActivity().startService(intent2);
					}
				}
			}
			// 返回首页
			else if (action != null
					&& Constants.MAIN_RETURN_HOME_ACTION.equals(action)) {
				CommonUtil.retHomeFragment(getActivity());
			}
			// 电话界面导航
			else if (action != null
					&& Constants.MAIN_NAVI_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_NAVI_ACTION),
						SpeechVoiceData.class);

				svd.setCommand(Constants.MAIN_NAVI_COM);

				Log.i(TAG, intent.getStringExtra(Constants.MAIN_NAVI_ACTION));
				CommonUtil.processBroadcast(getActivity(), svd);
			}
			// 电话界面显示obd
			else if (action != null && Constants.MAIN_OBD_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_OBD_ACTION),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

				svd.setCommand(Constants.MAIN_OBD_COM);
				svd.setValue(vdc.getValue());
				CommonUtil.processBroadcast(getActivity(), svd);
			}
			// 导航界面打电话
			else if (action != null
					&& Constants.MAIN_PHONE_ACTION.equals(action)) {

				svd = gson.fromJson(
						intent.getStringExtra(Constants.MAIN_PHONE_ACTION),
						SpeechVoiceData.class);
				vdc = gson.fromJson(svd.getValue(), VoiceDataClass.class);

				svd.setCommand(Constants.MAIN_PHONE_COM);
				svd.setValue(vdc.getValue());
				CommonUtil.processBroadcast(getActivity(), svd);
			}
		}
	};

	/**
	 * 广播过滤器
	 * 
	 * @return
	 */
	private static IntentFilter makeNewMsgIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.COMMON_UTIL_ACTION);
		intentFilter.addAction(Constants.MAIN_MUSIC_ACTION);
		intentFilter.addAction(Constants.MAIN_RETURN_HOME_ACTION);
		intentFilter.addAction(Constants.MAIN_NAVI_ACTION);
		intentFilter.addAction(Constants.MAIN_PHONE_ACTION);
		intentFilter.addAction(Constants.MAIN_OBD_ACTION);

		return intentFilter;
	}

	@Override
	public void onClick(View v) {
		// switch (v.getId()) {
		// case R.id.btn1:// 下一页
		// setDownPage(listMusic);
		// break;
		// case R.id.btn2:// 根绝歌曲名称搜索歌曲列表 首页最多显示5条
		// getSearchMusicSong("偏爱");
		// break;
		// case R.id.btn3:// 根绝歌手搜索歌曲列表首页最多显示5条
		// getSearchMusicSinger("陈奕迅");
		// break;
		// case R.id.btn4:// 音乐列表界面显示所有歌曲的前五条
		// getAllMusic();
		// break;
		// case R.id.btn5:// 上一页
		// setUpPage(listMusic);
		// break;
		// case R.id.btn6:// 选择某一条
		// // Intent intent = new Intent(getActivity(), MusicActivity.class);
		// // intent.putExtra("id", up + 0);// 第一条item为0
		// // startActivity(intent);
		// SpeechVoiceData data = new SpeechVoiceData();
		// data.setCommand(Constants.MAIN_MUSIC_PLAY_COM);
		// data.setValue("0");
		// CommonUtil.processBroadcast(getActivity(), data);
		// break;
		// default:
		// break;
		// }
	}

	/**
	 * 获取向上翻页的列表
	 * 
	 * @param listMusic
	 */
	public void setUpPage(List<DataMusicClass> listMusic) {
		// if (adapter != null && adapter.getCount() > 0) {
		// listView.removeAllViews();
		// adapter = null;
		// }
		if (adapter != null && adapter.setListMusicIsNull()) {
			Log.i(TAG, "setUpPage上次的adapter清空完成");
		}
		if (listMusic.size() > 5) {
			if (up >= 5) {
				up = up - 5;
				down = up + 5;
			}
			List<DataMusicClass> pageList = new ArrayList<DataMusicClass>();
			for (int i = up; i <= down; i++) {
				pageList.add(listMusic.get(i));
			}
			adapter = new MusicAdapter(pageList, getActivity());
			listView.setAdapter(adapter);
		}
	}

	/**
	 * 获取向下翻页的列表
	 * 
	 * @param listMusic
	 */
	public void setDownPage(List<DataMusicClass> listMusic) {
		if (adapter != null && adapter.setListMusicIsNull()) {
			Log.i(TAG, "setDownPage上次的adapter清空完成");
		}
		if (listMusic.size() > 5) {
			if (down < listMusic.size() - 1) {
				up = up + 5;
				down = down + 5;
				if (down > listMusic.size() - 1) {
					down = listMusic.size() - 1;
				}
			}
			List<DataMusicClass> pageList = new ArrayList<DataMusicClass>();
			for (int i = up; i <= down; i++) {
				pageList.add(listMusic.get(i));
			}
			adapter = new MusicAdapter(pageList, getActivity());
			listView.setAdapter(adapter);
		}
	}

	/**
	 * 获取所有歌曲列表 并显示前五条
	 */
	public void getAllMusic() {
		up = 0;
		down = 0;
		if (adapter != null && adapter.setListMusicIsNull()) {
			Log.i(TAG, "getSearchMusicSinger上次的adapter清空完成");
		}
		listMusic = MusicList.getMusicData(getActivity()
				.getApplicationContext());
		musicLsts = listMusic.size();
		if (listMusic.size() <= 5) {
			adapter = new MusicAdapter(listMusic, getActivity());
			listView.setAdapter(adapter);
		} else {
			List<DataMusicClass> list = new ArrayList<DataMusicClass>();
			for (int i = 0; i < 5; i++) {
				list.add(listMusic.get(i));
			}
			adapter = new MusicAdapter(list, getActivity());
			listView.setAdapter(adapter);
		}
		up = 0;
		down = 4;
	}

	/**
	 * 根据歌手搜索歌曲 并显示前五条
	 * 
	 * @param singer
	 */
	public boolean getSearchMusicSinger(String singer) {
		if (adapter != null && adapter.setListMusicIsNull()) {
			Log.i(TAG, "getSearchMusicSinger上次的adapter清空完成");
		}
		up = 0;
		down = 0;
		List<DataMusicClass> musicSinger = MusicList.getMusicBySinger(singer,
				listMusic);
		if (musicSinger == null || musicSinger.size() == 0) {
			return false;
		}
		if (musicSinger.size() <= 5) {
			adapter = new MusicAdapter(musicSinger, getActivity());
			listView.setAdapter(adapter);
		} else {
			List<DataMusicClass> list = new ArrayList<DataMusicClass>();
			for (int i = 0; i < 5; i++) {
				list.add(musicSinger.get(i));
			}
			adapter = new MusicAdapter(list, getActivity());
			listView.setAdapter(adapter);
		}
		up = 0;
		down = 4;
		listTypeMusic = musicSinger;
		return true;
	}

	/**
	 * 根据歌曲名称搜索歌曲并显示前五条
	 * 
	 * @param song
	 */
	public boolean getSearchMusicSong(String song) {
		up = 0;
		down = 0;
		if (adapter != null && adapter.setListMusicIsNull()) {
			Log.i(TAG, "getSearchMusicSong上次的adapter清空完成");
		}
		List<DataMusicClass> musicSong = MusicList.getMusicBySong(song,
				listMusic);
		if (musicSong == null || musicSong.size() == 0) {
			return false;
		}
		if (musicSong.size() <= 5) {
			adapter = new MusicAdapter(musicSong, getActivity());
			listView.setAdapter(adapter);
		} else {
			List<DataMusicClass> list = new ArrayList<DataMusicClass>();
			for (int i = 0; i < 5; i++) {
				list.add(musicSong.get(i));
			}
			adapter = new MusicAdapter(list, getActivity());
			listView.setAdapter(adapter);
		}
		up = 0;
		down = 4;
		listTypeMusic = musicSong;
		return true;
	}
}
